package com.shijie.service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import tk.mybatis.mapper.entity.Condition;

import com.shijie.component.ErpUserService;
import com.shijie.core.AbstractService;
import com.shijie.core.ServiceException;
import com.shijie.domain.entity.AdminRoles;
import com.shijie.domain.entity.Admins;
import com.shijie.mapper.AdminsMapper;
import com.shijie.utils.MD5Util;


/*
 *  @author: smart boy
 *  @date: 2018-08-06
 */
@Service
public class AdminsService extends AbstractService<Admins> {

	@Resource
	private AdminsMapper adminsMapper;
	@Resource
	private AdminRolesService adminRolesService;
	@Autowired
	private ErpUserService erpUserService;

	public Admins getAdminByLoginNameAndPassword(String loginName,
			String password) {
		Admins admin = new Admins();
		if (loginName != null) {
			admin.setLoginName(loginName);
		}
		if (password != null) {
			admin.setPassword(password);
		}
		admin.setDelFlag(0);
		return adminsMapper.selectOne(admin);
	}

	public void updateAdmin(Admins admin) {
		adminsMapper.updateByPrimaryKeySelective(admin);
	}

	@Transactional
	public void deleteById(Integer id) {
		Admins admin = adminsMapper.selectByPrimaryKey(id);
		if (admin == null) {
			throw new ServiceException("账号不存在，不能删除！");
		}
		if (admin.getBrandId() != null) {
			throw new ServiceException("品牌代理商账号，不能删除！");
		}
		Admins updateAdmin = new Admins();
		updateAdmin.setId(id);
		updateAdmin.setDelFlag(1);
		adminsMapper.updateByPrimaryKeySelective(updateAdmin);
	}

	@Transactional
	public void save(Admins admin) {
		if (admin.getId() == null) {
			admin.setSalt(UUID.randomUUID().toString());
			admin.setDelFlag(0);
			admin.setCreateBy(erpUserService.getUserName());
			admin.setCreateTime(DateTime.now().toDate());
			admin.setPassword(MD5Util.MD5Encode(
					admin.getLoginName() + admin.getPassword()
							+ admin.getSalt(), "UTF-8").toString());
			adminsMapper.insert(admin);
			
			List<AdminRoles> insertList = new ArrayList<>();
			for(Integer roleId : admin.getRoleIdList()){
				AdminRoles adminRole = new AdminRoles();
				adminRole.setUserId(admin.getId());
				adminRole.setRoleId(roleId);
				insertList.add(adminRole);
			}
			adminRolesService.save(insertList);
		} else {
			Admins adminx = adminsMapper.selectByPrimaryKey(admin.getId());
			admin.setPassword(MD5Util.MD5Encode(
					admin.getLoginName() + admin.getPassword()
							+ adminx.getSalt(), "UTF-8").toString());
			admin.setUpdateBy(erpUserService.getUserName());
			admin.setUpdateTime(DateTime.now().toDate());
			adminsMapper.updateByPrimaryKey(admin);
			Condition condition = new Condition(AdminRoles.class);
			condition.createCriteria().andEqualTo("userId", admin.getId());
			List<AdminRoles> list = adminRolesService
					.selectByCondition(condition);

			StringBuffer sb = new StringBuffer();
			list.forEach(c -> {
				sb.append(c.getId()).append(",");
			});

			if (sb.toString().length() > 0) {
				adminRolesService.deleteByIds(sb.substring(0,
						sb.lastIndexOf(",")));
			}

			List<AdminRoles> insertList = new ArrayList<>();
			for(Integer roleId : admin.getRoleIdList()){
				AdminRoles adminRole = new AdminRoles();
				adminRole.setUserId(admin.getId());
				adminRole.setRoleId(roleId);
				insertList.add(adminRole);
			}
			adminRolesService.save(insertList);
		}
	}

}
